package com.aauedu.springboot.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;
import javax.servlet.Servlet;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;

/**
 * 编写配置类
 */
@Configuration
public class DruidDataSourceConfig {

    //编写方法，注入DruidDataSource
    //问题：为什么我们注入了自己的DataSource，默认的HiKariDataSource就失效了?
    //1、默认的数据源是如何配置的？	@ConditionalOnMissingBean({ DataSource.class, XADataSource.class })
    //解读：通过@ConditionalOnMissingBean({DataSource.class})判断如果容器中有DataSource Bean，不注入原有的HiKari默认的数据源
    //2、debug源码
    @Bean
    @ConfigurationProperties("spring.datasource")
    public DataSource druidDataSource() throws SQLException {
        //1.编写配置@ConfigurationProperties("spring.datasource")后就可读取到application.yml的配置
        //2.我们就不需要调用@DruidDataSource对象的setxxx，会自动关联
        DruidDataSource druidDataSource = new DruidDataSource();
        //加入监控功能,加入防火墙监控
        druidDataSource.setFilters("stat, wall");
        return druidDataSource;
    }

    //配置Druid的监控页功能
    @Bean
    public ServletRegistrationBean statViewServlet() {
        //创建StateViewServlet
        StatViewServlet statViewServlet = new StatViewServlet();
        ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>(statViewServlet, "/druid/*");
        //设置init-parameter,设置用户名和密码
        registrationBean.addInitParameter("loginUsername", "bxl");
        registrationBean.addInitParameter("loginPassword", "666");
        return registrationBean;
    }

    // 配置WebStatFilter 用于采集 web-jdbc 关联监控的数据。
    @Bean
    public FilterRegistrationBean webStatFilter() {
        //创建WebStatFilter
        WebStatFilter webStatFilter = new WebStatFilter();
        FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<>(webStatFilter);
        //默认对所有的url请求进行监控
        filterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
        //排除指定的url
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }


}
